﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HealthManagement.Model;
using Telerik.Windows.Controls;
using HealthManagement.Data.Service;
using HealthManagement.Data.Model;
using Telerik.Windows.Controls.Charting;
using PM.Controls.Common;
using System.Threading;
using System.Windows.Threading;

namespace HealthManagement.View
{
    /// <summary>
    /// UserPanel.xaml 的交互逻辑
    /// </summary>
    public partial class UserPanel : Page
    {
        UserService ser = new UserService();
        IList<UserModel> users;
        public UserPanel()
        {
            InitializeComponent();

            RadChart rc = RadChart1;

            
            //rc.DefaultView.ChartLegend.Style = Application.Current.FindResource("CustomLegendItemStyle") as Style;
            rc.DefaultView.ChartLegend.Foreground = Application.Current.FindResource("text") as Brush;
            rc.DefaultView.ChartLegend.Background = new SolidColorBrush(Colors.Transparent);
            rc.DefaultView.ChartLegend.LegendItemStyle = Application.Current.FindResource("ChartLegendItemStyle") as Style;
            rc.DefaultView.ChartArea.AxisX.Visibility = Visibility.Collapsed;
            //rc.DefaultView.ChartArea.AxisX.AxisStyles.ItemLabelStyle = Application.Current.FindResource("XItemLabelStyle") as Style;
            //rc.DefaultView.ChartArea.AxisY.AxisStyles.GridLineStyle = Application.Current.FindResource("YGridLineStyle") as Style;
            rc.DefaultView.ChartArea.AxisY.AxisStyles.ItemLabelStyle = Application.Current.FindResource("XItemLabelStyle") as Style;
            rc.DefaultView.ChartArea.AxisY.ExtendDirection = AxisExtendDirection.Both;
            rc.DefaultView.ChartArea.AxisY.MinorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            rc.DefaultView.ChartArea.AxisY.PlotAreaAxisVisibility = Visibility.Collapsed;

            this.Loaded += new RoutedEventHandler(UserPanel_Loaded);
            
        }

        void UserPanel_Loaded(object sender, RoutedEventArgs e)
        {
            var list = ser.LoadMeasureUserList();

            initMeasureType();
            initUsersData(list);
            
        }

        private void initUsersData(IList<MeasureUser> list)
        {
            users = new List<UserModel>();
            int i = 0;
            foreach (var user in list)
            {
                users.Add(new UserModel()
                {
                    UserId = user.userId,
                    Name = user.username,
                    Photo = "/Images/EmpID" + ++i + ".jpg",
                    Mobile = user.MobilePhoneNumber,
                    Address = user.Address,
                    Age = user.Age,
                    Birthday = user.Birthday == null ? default(DateTime).ToShortDateString()
                    : user.Birthday.Value.ToShortDateString(),
                    Email = user.email,
                    Height = user.Height,
                    BloodType = user.BloodType,
                    IdCard = user.IdCard
                });
            }
            userList.ItemsSource = users;

            
            if (list.Count > 0)
            {
                //选择病人->触发默认血压的 checked时间->查询血压数据
                userList.SelectedIndex = 0;
                //默认选择血压，然后读取血压数据
                btnPressure.IsChecked = true;
                //query(MeasureCategory.BloodPressure);
            }
            else
            {
                RadChart1.ItemsSource = null;
                radGridView.ItemsSource = null;
            }
        }

        private void initMeasureType()
        {
            MeasureConditionServices service = new MeasureConditionServices();
            var list = service.Find(c => 1 == 1);
            list.Insert(0, new MeasureCondition { Id = "0", name = "所有" });
            comboState.ItemsSource = list;
            comboState.SelectedIndex = 0;
        }

        private Path CreateLinePath()
        {
            Path newPath = new Path();
            PathFigureCollectionConverter figureConverter = new PathFigureCollectionConverter();
            object geometryFigures = figureConverter.ConvertFromString("M30,347 L307.5,347");
            PathGeometry newGeometry = new PathGeometry();
            newPath.Stretch = Stretch.Fill;
            BrushConverter brushConverter = new BrushConverter();
            newPath.Stroke = (Brush)brushConverter.ConvertFromString("#FF0998f8");
            newPath.StrokeThickness = 2;
            newGeometry.Figures = (PathFigureCollection)geometryFigures;
            newPath.Data = (Geometry)newGeometry;
            return newPath;
        }


        //按名字的首字母进行选择
        private void RadButton_Click(object sender, RoutedEventArgs e)
        {
            string key = (sender as RadButton).Content.ToString().ToLower();
            var list = ser.LoadMeasureUserList(c => c.username.ToLower().StartsWith(key));

            initUsersData(list);
            
        }

        //选择所有用户
        private void RadButtonAll_Click(object sender, RoutedEventArgs e)
        {
            UserPanel_Loaded(null, null);
        }

        //开始测量
        private void btnMeasure_click(object sender, RoutedEventArgs e)
        {
            Application.Current.Properties["selectedUser"] = userList.SelectedItem;
            NavigationService.GetNavigationService(this).
                Navigate(new Uri("/View/MeterPanel.xaml", UriKind.Relative));
        }

        
        private void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string key = (sender as RadWatermarkTextBox).Text.Trim().ToLower();

            if (key.Length > 0)
            {
                var list = ser.LoadMeasureUserList(c => c.username.ToLower().Contains(key));

                initUsersData(list);
            }
        }

        private void userList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserModel selectedUser = (sender as ListBox).SelectedItem as UserModel;
            
            if (selectedUser != null)
            {
                appearance.DataContext = selectedUser;

                //重置，如果已经选择，切换用户不会刷新列表
                btnPressure.IsChecked = false;
                btnPressure.IsChecked = true;
            }
        }


        private void query_click(object sender, RoutedEventArgs e)
        {
            if (btnPressure.IsChecked.Value)
                query(MeasureCategory.BloodPressure);
            if (btnGlucose.IsChecked.Value)
                query(MeasureCategory.BloodGlucose);
            if (btnOxygen.IsChecked.Value)
                query(MeasureCategory.OxygenSaturation);
            if (btnTemperature.IsChecked.Value)
                query(MeasureCategory.BodyTemperature);
            if (btnECG.IsChecked.Value)
                query(MeasureCategory.ECG);
        }

        private void query(MeasureCategory type)
        {
            UserModel selectedUser = userList.SelectedItem as UserModel;
            
            DateTimeOffset start = timeStart.SelectedValue.Value;
            DateTimeOffset end = timeEnd.SelectedValue.Value;

            MeasureCondition mc = comboState.SelectedItem as MeasureCondition;

            switch (type)
            {
                case MeasureCategory.BloodPressure:
                    BloodPressureService preSer = new BloodPressureService();

                    var preList = preSer.Find(c => c.measureUserId == selectedUser.UserId
                        && c.measureTime >= start && c.measureTime <= end
                        && c.measureConditionCode == (mc.Id == "0" ? c.measureConditionCode : mc.Id),
                        new Func<BloodPressure, DateTimeOffset>[]
                        {
                            new Func<BloodPressure,DateTimeOffset>(c=>c.measureTime.Value) 
                        },
                        new bool[] { true }, 1, 1000)
                        .ToList();
                    MeasureDataFill.GenerateBloodPressure(radGridView, RadChart1, preList);
                    break;
                case MeasureCategory.BloodGlucose:
                    BloodSugarService sugarSer = new BloodSugarService();
                    var sugarList = sugarSer.Find(c => c.measureUserId == selectedUser.UserId
                        && c.measureTime >= start && c.measureTime <= end
                        && c.measureConditionCode == (mc.Id == "0" ? c.measureConditionCode : mc.Id),
                        new Func<BloodSugar, DateTimeOffset>[]
                        {
                            new Func<BloodSugar,DateTimeOffset>(c=>c.measureTime.Value) 
                        },
                        new bool[] { true }, 1, 1000)
                        .ToList();
                    MeasureDataFill.GenerateBloodGlucose(radGridView, RadChart1, sugarList);
                    break;
                case MeasureCategory.OxygenSaturation:
                    BloodOxygenService oxySer = new BloodOxygenService();
                    var oxyList = oxySer.Find(c => c.measureUserId == selectedUser.UserId
                        && c.measureTime >= start && c.measureTime <= end
                        && c.measureConditionCode == (mc.Id == "0" ? c.measureConditionCode : mc.Id),
                        new Func<BloodOxygen, DateTimeOffset>[]
                        {
                            new Func<BloodOxygen,DateTimeOffset>(c=>c.measureTime.Value) 
                        },
                        new bool[] { true }, 1, 1000)
                        .ToList();
                    MeasureDataFill.GenerateBloodOxygen(radGridView, RadChart1, oxyList);
                    break;
                case MeasureCategory.BodyTemperature:
                    BodyTemperatureService tempSer = new BodyTemperatureService();
                    var tempList = tempSer.Find(c => c.measureUserId == selectedUser.UserId
                        && c.measureTime >= start && c.measureTime <= end
                        && c.measureConditionCode == (mc.Id == "0" ? c.measureConditionCode : mc.Id),
                        new Func<BodyTemperature, DateTimeOffset>[]
                        {
                            new Func<BodyTemperature,DateTimeOffset>(c=>c.measureTime.Value) 
                        },
                        new bool[] { true }, 1, 1000)
                        .ToList();
                    MeasureDataFill.GenerateBodyTemperature(radGridView, RadChart1, tempList);
                    break;
                case MeasureCategory.ECG:
                    EcgService ecgSer = new EcgService();
                    var ecgList = ecgSer.Find(c => c.measureUserId == selectedUser.UserId
                        && c.measureTime >= start && c.measureTime <= end
                        && c.measureConditionCode == (mc.Id == "0" ? c.measureConditionCode : mc.Id),
                        new Func<ECG, DateTimeOffset>[]
                        {
                            new Func<ECG,DateTimeOffset>(c=>c.measureTime.Value) 
                        },
                        new bool[] { true }, 1, 1000)
                        .ToList();
                    MeasureDataFill.GenerateECG( radGridView,RadChart1, ecgList);
                    break;
                default:
                    break;
            }

        }

        #region 测量类型checkbox选中事件

        private void btnPressure_Checked(object sender, RoutedEventArgs e)
        {
            tbType.Text = (sender as RadRadioButton).Tag.ToString();


            if (timeEnd.SelectedValue == null)
                timeEnd.SelectedValue = DateTime.Now;
            if (timeStart.SelectedValue == null)
                timeStart.SelectedValue = Convert.ToDateTime(timeEnd.SelectedValue).AddMonths(-1);

            //需要先设定 timePicker的初始化值，下面的查询需要用到
            query(MeasureCategory.BloodPressure);
        }

        private void btnGlucose_Checked(object sender, RoutedEventArgs e)
        {
            tbType.Text = (sender as RadRadioButton).Tag.ToString();

            if (timeEnd.SelectedValue == null)
                timeEnd.SelectedValue = DateTime.Now;
            if (timeStart.SelectedValue == null)
                timeStart.SelectedValue = Convert.ToDateTime(timeEnd.SelectedValue).AddMonths(-1);

            //需要先设定 timePicker的初始化值，下面的查询需要用到
            query(MeasureCategory.BloodGlucose);
        }

        private void btnOxygen_Checked(object sender, RoutedEventArgs e)
        {
            tbType.Text = (sender as RadRadioButton).Tag.ToString();

            if (timeEnd.SelectedValue == null)
                timeEnd.SelectedValue = DateTime.Now;
            if (timeStart.SelectedValue == null)
                timeStart.SelectedValue = Convert.ToDateTime(timeEnd.SelectedValue).AddMonths(-1);

            //需要先设定 timePicker的初始化值，下面的查询需要用到
            query(MeasureCategory.OxygenSaturation);
        }

        private void btnTemperature_Checked(object sender, RoutedEventArgs e)
        {
            tbType.Text = (sender as RadRadioButton).Tag.ToString();

            if (timeEnd.SelectedValue == null)
                timeEnd.SelectedValue = DateTime.Now;
            if (timeStart.SelectedValue == null)
                timeStart.SelectedValue = Convert.ToDateTime(timeEnd.SelectedValue).AddMonths(-1);

            //需要先设定 timePicker的初始化值，下面的查询需要用到
            query(MeasureCategory.BodyTemperature);
        }

        private void btnECG_Checked(object sender, RoutedEventArgs e)
        {
            tbType.Text = (sender as RadRadioButton).Tag.ToString();

            if (timeEnd.SelectedValue == null)
                timeEnd.SelectedValue = DateTime.Now;
            if (timeStart.SelectedValue == null)
                timeStart.SelectedValue = Convert.ToDateTime(timeEnd.SelectedValue).AddMonths(-1);

            //需要先设定 timePicker的初始化值，下面的查询需要用到
            query(MeasureCategory.ECG);
        }


        #endregion


        private void addUser_click(object sender, RoutedEventArgs e)
        {
            UserForm win = new UserForm();
            win.onSaveHandler += () => UserPanel_Loaded(null, null);
            win.ShowDialog();
        }


        private void edit_click(object sender, RoutedEventArgs e)
        {
            UserForm win = new UserForm((appearance.DataContext as UserModel).UserId);
            win.onSaveHandler += () => UserPanel_Loaded(null, null);
            win.ShowDialog();
        }


        private void delete_click(object sender, RoutedEventArgs e)
        {

            RadWindow.Confirm("是否要删除该用户？", new EventHandler<WindowClosedEventArgs>(OnConfirmClosed));

           
        }

        private void OnConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                string userid = (appearance.DataContext as UserModel).UserId;
                UserService ser = new UserService();
                var user = ser.Get("userId", userid);
                ser.Delete(user, "userId", "userId");

                this.UserPanel_Loaded(null, null);
            }
        }

        private void comboDate_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string s = comboDate.SelectedValue.ToString();
            if (s == "最近一周")
            {
                timeEnd.SelectedValue = DateTime.Now;
                int day = Convert.ToInt32(DateTime.Now.DayOfWeek);
                if (day == 0)
                    day = 7;
                timeStart.SelectedValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day-(day - 1)); 
            }

            if (s == "最近一个月")
            {
                timeEnd.SelectedValue = DateTime.Now;
                timeStart.SelectedValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            }
        }



    }

    class MeasureDataFill
    {
        private static Style gvStyle = Application.Current.FindResource("GridViewHeaderCellStyle") as Style;

        public static void GenerateBloodPressure(RadGridView gv, RadChart rc, IList<BloodPressure> list)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            col = new GridViewDataColumn();
            col.Header = "测量条件";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureCondition.name");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "测量时间";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureTimeStr");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "舒张压";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("DBP");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            col = new GridViewDataColumn();
            col.Header = "收缩压";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("SBP");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            col = new GridViewDataColumn();
            col.Header = "心率";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("Pulse");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            gv.ItemsSource = list;
            #endregion

            list = list.OrderBy(c => c.measureTime.Value).ToList();

            #region chart

            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "血压";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "收缩压";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "舒张压";
            mapping.CollectionIndex = 1;

            def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue ));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "心率";
            mapping.CollectionIndex = 2;
            def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c => new ChartValue { Value = c.SBP == null ? 0 : c.SBP.Value, Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());
            data.Add(list.Select(c => new ChartValue { Value = c.DBP == null ? 0 : c.DBP.Value, Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());
            data.Add(list.Select(c => new ChartValue { Value = c.Pulse == null ? 0 : c.Pulse.Value, Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());


            rc.ItemsSource = data;

            #endregion
        }

        public static void GenerateBloodGlucose(RadGridView gv, RadChart rc, IList<BloodSugar> list)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            col = new GridViewDataColumn();
            col.Header = "测量条件";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureCondition.name");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "测量时间";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureTimeStr");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "血糖(MMOL/L)";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("sugarValue");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            gv.ItemsSource = list;
            #endregion

            list = list.OrderBy(c => c.measureTime.Value).ToList();

            #region chart
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "血糖";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "血糖";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);


            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c => new ChartValue { Value = c.sugarValue == null ? 0 :Convert.ToDecimal( c.sugarValue.Value), Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());


            rc.ItemsSource = data;

            #endregion
        }

        public static void GenerateBloodOxygen(RadGridView gv, RadChart rc, IList<BloodOxygen> list)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            col = new GridViewDataColumn();
            col.Header = "测量条件";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureCondition.name");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "测量时间";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureTimeStr");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "血氧饱和度(%)";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("oxValue");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            col = new GridViewDataColumn();
            col.Header = "心率(次/分)";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("Pulse");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            gv.ItemsSource = list;
            #endregion

            list = list.OrderBy(c => c.measureTime.Value).ToList();

            #region chart

            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "血氧";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "血氧饱和度";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "血氧脉率";
            mapping.CollectionIndex = 1;
            def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c => new ChartValue { Value = c.oxValue == null ? 0 : Convert.ToDecimal(c.oxValue.Value), Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());
            data.Add(list.Select(c => new ChartValue { Value = string.IsNullOrEmpty(c.Pulse) ? 0 : Convert.ToDecimal(c.Pulse), Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());

            rc.ItemsSource = data;
            #endregion
        }

        public static void GenerateBodyTemperature(RadGridView gv, RadChart rc, IList<BodyTemperature> list)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            col = new GridViewDataColumn();
            col.Header = "测量条件";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureCondition.name");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "测量时间";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureTimeStr");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "耳温(°C)";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("tempValue");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            gv.ItemsSource = list;
            #endregion

            list = list.OrderBy(c => c.measureTime.Value).ToList();

            #region chart
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "耳温";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "耳温";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            //def.ItemToolTipFormat = "#VAL{yy年M月d日 hh点mm分}";
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value" , DataPointMember.YValue ));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c =>
                new ChartValue { Value = c.tempValue == null ? 0 : Convert.ToDecimal(c.tempValue.Value), Tooltip = c.measureTime.Value.ToString("yy年MM月dd日  hh：mm") }).ToList());

            rc.ItemsSource = data;

            #endregion
        }

        public static void GenerateECG(RadGridView gv, RadChart rc, IList<ECG> list)
        {
            if (list.Count == 0)
            {
                gv.ItemsSource = null;
                return;
            }

            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            col = new GridViewDataColumn();
            col.Header = "测量条件";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureCondition.name");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            col.Header = "测量时间";
            col.Width = GridViewLength.Auto;
            col.HeaderCellStyle = gvStyle;
            col.DataMemberBinding = new Binding("MeasureTimeStr");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            //col = new GridViewDataColumn();
            //col.Header = "值(°C)";
            //col.Width = GridViewLength.Auto;
            //col.HeaderCellStyle = gvStyle;
            //col.DataMemberBinding = new Binding("valuestr");
            //col.IsFilterable = false;
            //gv.Columns.Add(col);


            gv.ItemsSource = list;
            #endregion

            list = list.OrderBy(c => c.measureTime.Value).ToList();

            #region chart

            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = false;
            rc.DefaultView.ChartLegend.Header = "心电图";

            List<List<ChartValue>> lists = new List<List<ChartValue>>();
            DateTime now = DateTime.Now;
            for (int idx = 0; idx < list.Count; idx++)
            {
                SeriesMapping mapping = new SeriesMapping();
                mapping.LegendLabel = list[idx].measureTime.Value.ToString("yy年MM月dd日 HH:mm");
                mapping.CollectionIndex = idx;
                SplineSeriesDefinition def = new SplineSeriesDefinition();
                def.ItemLabelFormat = "0.#";
                def.ShowItemLabels = false;
                def.ShowPointMarks = false;
                def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
                mapping.SeriesDefinition = def;
                mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
                //mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XValue));
                rc.SeriesMappings.Add(mapping);

                
                List<ChartValue> ll = new List<ChartValue>();
                Random r = new Random();
                foreach(var i in list[idx].valueInt )
                {
                    ll.Add(new ChartValue { Value = i, Time = now.AddMilliseconds(100 * i) });
                }
                lists.Add(ll);
            }
            rc.ItemsSource = lists;

            /*
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.Annotations[0].Visibility = Visibility.Visible;

            Binding binding;
            BindingExpressionBase result;
            binding = new Binding { Path = new PropertyPath("Data") };
            result = BindingOperations.SetBinding(rc, RadChart.ItemsSourceProperty, binding);

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "心电图";
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = false;
            def.ShowPointMarks = false;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XValue));
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            rc.SeriesMappings.Add(mapping);
            rc.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "#VAL{hh:mm:ss}";
            rc.DefaultView.ChartArea.AxisX.LabelStep = 2;

            binding = new Binding { Path = new PropertyPath("AxisXMinValue") };
            result = BindingOperations.SetBinding(rc.DefaultView.ChartArea.AxisX, Axis.MinValueProperty, binding);
            binding = new Binding { Path = new PropertyPath("AxisXMaxValue") };
            result = BindingOperations.SetBinding(rc.DefaultView.ChartArea.AxisX, Axis.MaxValueProperty, binding);
            binding = new Binding { Path = new PropertyPath("AxisXStep") };
            result = BindingOperations.SetBinding(rc.DefaultView.ChartArea.AxisX, Axis.StepProperty, binding);

            binding = new Binding { Path = new PropertyPath("AxisYMinValue") };
            result = BindingOperations.SetBinding(rc.DefaultView.ChartArea.AxisY, Axis.MinValueProperty, binding);
            binding = new Binding { Path = new PropertyPath("AxisYMaxValue") };
            result = BindingOperations.SetBinding(rc.DefaultView.ChartArea.AxisY, Axis.MaxValueProperty, binding);
            binding = new Binding { Path = new PropertyPath("AxisYStep") };
            result = BindingOperations.SetBinding(rc.DefaultView.ChartArea.AxisY, Axis.StepProperty, binding);

            List<int> ll = new List<int>();
            Random r = new Random();
            for (int i = 0; i < 100000; i++)
            {
                ll.Add(r.Next(20, 120));
            }

            //list.RemoveAll(c => c.EcgValues == null || c.EcgValues.Length == 0);
            //if (list.Count == 0)
            //    return;


            rc.DefaultView.ChartArea.EnableAnimations = false;

            MeasureDataFill.rc = rc;
            MeasureDataFill.list = ll;
            MeasureDataFill.ecgModel = new ChartModel(frec);
            ecgModel.AxisYMaxValue = (int)(ll.Max() * 1.1);
            ecgModel.AxisYMinValue = (int)(ll.Min() * 0.9);
            ecgModel.AxisYMinValue = ecgModel.AxisYMinValue / 10 * 10;
            ecgModel.AxisYStep = 20;
            ecgModel.YIntercept = Convert.ToInt32((ll.Max() + ll.Min()) / 2);

            //DateTime now=DateTime.Now;
            //List<ChartValue> lll = new List<ChartValue>();
            //ecgModel = new ChartModel(10000);
            //ecgModel.Data = new Queue<ChartValue>();
            //for (int i=0;i<ll.Count;i++)
            //{
            //    ChartValue v = new ChartValue();
            //    v.Time=now.AddSeconds(i);
            //    v.Value = ll[i];
            //    lll.Add(v);
            //    ecgModel.Data.Enqueue(v);
            //}

            container.DataContext = ecgModel;

            MeasureDataFill.idx = 0;

            DispatcherTimer timer1 = new DispatcherTimer();
            timer1.Interval = TimeSpan.FromMilliseconds(1000.0 / fps);
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Start();
            */

            #endregion

        }

        /*
        static RadChart rc;
        static List<int> list;
        static ChartModel ecgModel;
        static int idx;
        //频率
        static int frec = 250;

        //帧数
        static int fps = 1;

        //每次读取个数
        static int units = frec / fps;

        static void timer1_Tick(object sender, EventArgs e)
        {
            DispatcherTimer t = sender as DispatcherTimer;

            DateTime now = DateTime.Now;
            List<int> l = list.Skip(idx * units).Take(units).ToList();
            if (l.Count <= units)
            {
                for (int i = l.Count; i < units; i++)
                {
                    l.Add(0);
                }
               
            }
            idx++;

            ecgModel.EnqueueValue(l, now);
            ecgModel.SetUpAxisXRange(now);

            ecgModel.Data = null;
            ecgModel.Data = ecgModel.CpuData;

            foreach (var i in ecgModel.Data)
            {
                if (i.Value != 0)
                    return;
            }

            t.Stop();

            

        }
        */


        private static double str2Double(string str)
        {
            if (string.IsNullOrEmpty(str))
                return 0;
            return double.Parse(str);
        }

        private static float str2Float(string str)
        {
            if (string.IsNullOrEmpty(str))
                return 0;
            return float.Parse(str);
        }
    }
}
